package com.quanyan.messagepush.service.impl;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.messagepush.enums.PushApplication;
import com.quanyan.messagepush.service.MessagePushService;
import com.quanyan.messagepush.vo.GtConfigVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Zheng.Ke
 * Date 2016/6/28.
 */
@Service("messagePushService")
public class GtMessagePushServiceImpl implements MessagePushService {
    private static Logger logger = LoggerFactory.getLogger(GtMessagePushServiceImpl.class);

    @Override
    public APIResponse pushMessageToSingleForIOS(PushApplication pushApplication, String pushText, String deviceToken) {
        try {
            if (pushApplication == null) {
                return APIResponse.returnFail("推送项目不能为空");
            }
            if (StringUtil.isBlankOrNull(pushText)) {
                return APIResponse.returnFail("pushText不能为空");
            }
            if (StringUtil.isBlankOrNull(deviceToken)) {
                return APIResponse.returnFail("deviceToken不能为空");
            }
            // 获取配置参数
            GtConfigVo gtConfigVo = getGtConfigVoByPushApplication(pushApplication);
            String appId = gtConfigVo.getAppId();
            String url = gtConfigVo.getUrl();
            String appKey = gtConfigVo.getAppKey();
            String masterSecret = gtConfigVo.getMasterSecret();

            IGtPush push =  new IGtPush(url, appKey, masterSecret);

            // 透传模块
            TransmissionTemplate template = new TransmissionTemplate();
            template.setAppId(appId);
            template.setAppkey(appKey);
            template.setTransmissionContent("透传内容");
            template.setTransmissionType(1);

            APNPayload payload = new APNPayload();
            payload.setAlertMsg(new APNPayload.SimpleAlertMsg(pushText));
            template.setAPNInfo(payload);

            SingleMessage singleMessage = new SingleMessage();
            singleMessage.setData(template);
            singleMessage.setOfflineExpireTime(2 * 60 * 60 * 1000);// 2小时

            IPushResult result = push.pushAPNMessageToSingle(appId, deviceToken, singleMessage);

            if (result != null) {
                if (!"ok".equals(result.getResponse().get("result"))) {
                    return APIResponse.returnFail("个推异常提示：" + result.getResponse().toString());
                }
            } else {
                return APIResponse.returnFail("个推服务器响应异常");
            }

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    @Override
    public APIResponse pushMessageToSingleForAndroid(PushApplication pushApplication, String pushText, String cid) {
        try {
            if (pushApplication == null) {
                return APIResponse.returnFail("推送项目不能为空");
            }
            if (StringUtil.isBlankOrNull(pushText)) {
                return APIResponse.returnFail("pushText不能为空");
            }
            if (StringUtil.isBlankOrNull(cid)) {
                return APIResponse.returnFail("cid不能为空");
            }

            // 获取配置参数
            GtConfigVo gtConfigVo = getGtConfigVoByPushApplication(pushApplication);
            String appId = gtConfigVo.getAppId();
            String url = gtConfigVo.getUrl();
            String appKey = gtConfigVo.getAppKey();
            String masterSecret = gtConfigVo.getMasterSecret();

            NotificationTemplate template = getNotificationTemplate(appId, appKey, pushText);

            Target target = new Target();
            target.setAppId(appId);
            target.setClientId(cid);

            SingleMessage message = new SingleMessage();
            message.setData(template);

            IGtPush push =  new IGtPush(url, appKey, masterSecret);

            IPushResult result = push.pushMessageToSingle(message, target);

            if (result != null) {
                System.out.println(result.getResponse().toString());
                if (!"ok".equals(result.getResponse().get("result"))) {
                    return APIResponse.returnFail("个推异常提示：" + result.getResponse().toString());
                }
            } else {
                return APIResponse.returnFail("个推服务器响应异常");
            }

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    @Override
    public APIResponse pushMessageToListForAndroid(PushApplication pushApplication, String pushText, List<String> cidList) {
        try {
            if (pushApplication == null) {
                return APIResponse.returnFail("推送项目不能为空");
            }
            if (StringUtil.isBlankOrNull(pushText)) {
                return APIResponse.returnFail("pushText不能为空");
            }
            if (cidList == null || cidList.size() <= 0) {
                return APIResponse.returnFail("cidList不能为空");
            }

            // 获取配置参数
            GtConfigVo gtConfigVo = getGtConfigVoByPushApplication(pushApplication);
            String appId = gtConfigVo.getAppId();
            String url = gtConfigVo.getUrl();
            String appKey = gtConfigVo.getAppKey();
            String masterSecret = gtConfigVo.getMasterSecret();

            NotificationTemplate template = getNotificationTemplate(appId, appKey, pushText);

            List<Target> targets = new ArrayList<Target>();
            for (int i=0; i<cidList.size(); i++) {
                String cid = cidList.get(i);
                if (!StringUtil.isBlankOrNull(cid)) {
                    Target target = new Target();
                    target.setAppId(appId);
                    target.setClientId(cid);
                    targets.add(target);
                }
            }

            IGtPush push =  new IGtPush(url, appKey, masterSecret);
            ListMessage message = new ListMessage();
            message.setData(template);

            // taskId用于在推送时去查找对应的message
            String taskId = push.getContentId(message);
            IPushResult result = push.pushMessageToList(taskId, targets);

            if (result != null) {
                System.out.println(result.getResponse().toString());
                if (!"ok".equals(result.getResponse().get("result"))) {
                    return APIResponse.returnFail("个推异常提示：" + result.getResponse().toString());
                }
            } else {
                return APIResponse.returnFail("个推服务器响应异常");
            }

            return APIResponse.returnSuccess();
        } catch (Exception e) {
            return APIResponse.returnFail(e.getMessage());
        }
    }

    private NotificationTemplate getNotificationTemplate(String appId, String appKey, String pushText) {
        NotificationTemplate template = new NotificationTemplate();

        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionContent("我是透传内容");
        template.setTransmissionType(1);
        template.setTitle("百灵鸟");
        template.setText(pushText);

        return template;
    }

    private GtConfigVo getGtConfigVoByPushApplication(PushApplication pushApplication) {
        String appId = null;
        String appKey = null;
        String masterSecret = null;
        String url = "http://sdk.open.api.igexin.com/apiex.htm";
        switch (pushApplication) {
            case LARK_PARTICIPATOR_TEST :
                appId = "blSYThvGA46A0ZWiCwQes1";
                appKey = "47W84KMgIw5rj9LLhLrOt1";
                masterSecret = "5pdzgR2LMR6n2zTUbdNIh6";
                break;
            case GETUI_APP_DEMO :
                appId = "v6s8lxuTtd9Q7j5CWXzJD9";
                appKey = "dnQhXYwLPs9UAji9b6UjQ5";
                masterSecret = "24YwIqI3tu74eo7B3rML8A";
                break;
        }

        GtConfigVo gtConfigVo = new GtConfigVo();
        gtConfigVo.setAppId(appId);
        gtConfigVo.setAppKey(appKey);
        gtConfigVo.setMasterSecret(masterSecret);
        gtConfigVo.setUrl(url);

        return gtConfigVo;
    }

}
